package com.chenjian.annotation.dao;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidPooledConnection;
import com.chenjian.annotation.custom.anno.CustomAutowired;
import com.chenjian.annotation.custom.anno.CustomService;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * @author 应癫
 */

@CustomService
public class ConnectionUtils {

    //将连接存储到线程中
    private ThreadLocal<Connection> threadLocal = new ThreadLocal<>();


    /**
     * 从当前线程获取连接
     */
    public Connection getCurrentThreadConn() throws SQLException {
        /**
         * 判断当前线程中是否已经绑定连接，如果没有绑定，需要从连接池获取一个连接绑定到当前线程
         */
        Connection connection = threadLocal.get();
        if (connection == null) {
            connection = DataSources.getDataSources().getConnection();
            // 绑定到当前线程
            threadLocal.set(connection);
        }
        return connection;

    }
}
